package cn.uncode.springcloud.starter.bus.mq.rabbit;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import lombok.extern.slf4j.Slf4j;

//@Configuration
@Slf4j
public class RibbitMQAutoConfiguration {
	@Value("${spring.rabbitmq.queuename}")
	private String queueName;
	@Value("${spring.rabbitmq.exchange}")
	private String queueExchange;
	@Value("${spring.rabbitmq.routingkey}")
	private String routingkey;
	 
//    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    
//    @Bean
//    @ConfigurationProperties(prefix="spring.rabbitmq")
    public ConnectionFactory connectionFactory(){
    	return new CachingConnectionFactory (); //publisherConfirms 消息确认回调
    }
    
//    @Bean
    public RabbitTemplate template(ConnectionFactory connectionFactory, MessageConverter converter) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        //template.setChannelTransacted(false);
        //1 构造template, exchange, routingkey等
        //2 设置message序列化方法
        //3 设置发送确认
        template.setMandatory(true);
        template.setExchange(queueExchange);
        template.setRoutingKey(routingkey);
        template.setMessageConverter(converter);
        //2
        template.setMessageConverter(new Jackson2JsonMessageConverter());
//        RetryCache retryCache = new RetryCache();
//
//        //3
//        template.setConfirmCallback((correlationData, ack, cause) -> {
//            if (!ack) {
//                log.info("send message failed: " + cause + correlationData.toString());
//            } else {
//                retryCache.del(correlationData.getId());
//            }
//        });
//
//        template.setReturnCallback((message, replyCode, replyText, tmpExchange, tmpRoutingKey) -> {
//            try {
//                Thread.sleep(Constants.ONE_SECOND);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//
//            log.info("send message failed: " + replyCode + " " + replyText);
//            template.send(message);
//        });
//        retryCache.setSender(new RabbitmqTemplate(template, retryCache));
        return template;
    }

    @Bean
    public Queue queue() {
        return new Queue(queueName, true);
    }
    
}
